/*
  +----------------------------------------------------------------------+
  | PHP Version 7                                                        |
  +----------------------------------------------------------------------+
  | Copyright (c) 1997-2018 The PHP Group                                |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.php.net/license/3_01.txt                                  |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author:                                                              |
  +----------------------------------------------------------------------+
*/

/* $Id$ */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_snowflake.h"

/* If you declare any globals in php_snowflake.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(snowflake)
*/

/* True global resources - no need for thread safety here */
static int le_snowflake;

/* {{{ PHP_INI
 */
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
    STD_PHP_INI_ENTRY("snowflake.global_value",      "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_snowflake_globals, snowflake_globals)
    STD_PHP_INI_ENTRY("snowflake.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_snowflake_globals, snowflake_globals)
PHP_INI_END()
*/
/* }}} */

/* Remove the following function when you have successfully modified config.m4
   so that your module can be compiled into PHP, it exists only for testing
   purposes. */

/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_snowflake_compiled(string arg)
   Return a string to confirm that the module is compiled in */
PHP_FUNCTION(snowflake)
{
   
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <sched.h>
#include <linux/unistd.h>
#include <sys/syscall.h>
#include <errno.h>
#include <linux/types.h>
#include <time.h>
#include <stdint.h>
#include <sys/time.h>

    struct  globle
    {
        int global_int:12;
        uint64_t last_stamp;
        int workid;
        int seqid;
    };

    void set_workid(int workid);
    pid_t gettid( void );
    uint64_t get_curr_ms();
    uint64_t wait_next_ms(uint64_t lastStamp);
    int atomic_incr(int id);
    uint64_t get_unique_id();
    uint64_t get_snow_id(int workid);

    struct globle g_info;

#define sequenceMask (-1L ^ (-1L << 12L))

    void set_workid(int workid)
    {
        g_info.workid = workid;
    }

    pid_t gettid(void)
    {
        return syscall(__NR_gettid);
    }

    uint64_t get_curr_ms()
    {
        struct timeval time_now;
        gettimeofday(&time_now, NULL);
        uint64_t ms_time = time_now.tv_sec * 1000 + time_now.tv_usec / 1000;
        return ms_time;
    }

    uint64_t wait_next_ms(uint64_t lastStamp)
    {
        uint64_t cur = 0;
        do {
            cur = get_curr_ms();
        } while (cur <= lastStamp);
        return cur;
    }
    int atomic_incr(int id)
    {
        __sync_add_and_fetch( &id, 1 );
        return id;
    }

    uint64_t get_unique_id()
    {
        uint64_t uniqueId = 0;
        uint64_t nowtime = get_curr_ms();
        uniqueId = nowtime << 22;
        uniqueId |= (g_info.workid & 0x3ff) << 12;

        if (nowtime < g_info.last_stamp)
        {
            perror("error");
            exit(-1);
        }
        if (nowtime == g_info.last_stamp)
        {
            g_info.seqid = atomic_incr(g_info.seqid) & sequenceMask;
            if (g_info.seqid == 0)
            {
                nowtime = wait_next_ms(g_info.last_stamp);
            }
        }
        else
        {
            g_info.seqid  = 0;
        }
        g_info.last_stamp = nowtime;
        uniqueId |=g_info.seqid;
        return uniqueId;
    }
    set_workid(workid);
    int size;
    uint64_t unquie = get_unique_id();
    return unquie;
}
PHP_FUNCTION(confirm_snowflake_compiled)
{
	char *arg = NULL;
	size_t arg_len, len;
	zend_string *strg;

	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
		return;
	}

	strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "snowflake", arg);

	RETURN_STR(strg);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
   unfold functions in source code. See the corresponding marks just before
   function definition, where the functions purpose is also documented. Please
   follow this convention for the convenience of others editing your code.
*/


/* {{{ php_snowflake_init_globals
 */
/* Uncomment this function if you have INI entries
static void php_snowflake_init_globals(zend_snowflake_globals *snowflake_globals)
{
	snowflake_globals->global_value = 0;
	snowflake_globals->global_string = NULL;
}
*/
/* }}} */

/* {{{ PHP_MINIT_FUNCTION
 */
PHP_MINIT_FUNCTION(snowflake)
{
	/* If you have INI entries, uncomment these lines
	REGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MSHUTDOWN_FUNCTION
 */
PHP_MSHUTDOWN_FUNCTION(snowflake)
{
	/* uncomment this line if you have INI entries
	UNREGISTER_INI_ENTRIES();
	*/
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
 */
PHP_RINIT_FUNCTION(snowflake)
{
#if defined(COMPILE_DL_SNOWFLAKE) && defined(ZTS)
	ZEND_TSRMLS_CACHE_UPDATE();
#endif
	return SUCCESS;
}
/* }}} */

/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
 */
PHP_RSHUTDOWN_FUNCTION(snowflake)
{
	return SUCCESS;
}
/* }}} */

/* {{{ PHP_MINFO_FUNCTION
 */
PHP_MINFO_FUNCTION(snowflake)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "snowflake support", "enabled");
	php_info_print_table_end();

	/* Remove comments if you have entries in php.ini
	DISPLAY_INI_ENTRIES();
	*/
}
/* }}} */

/* {{{ snowflake_functions[]
 *
 * Every user visible function must have an entry in snowflake_functions[].
 */
const zend_function_entry snowflake_functions[] = {
	PHP_FE(snowflake,	NULL)
	PHP_FE(confirm_snowflake_compiled,	NULL)		/* For testing, remove later. */
	PHP_FE_END	/* Must be the last line in snowflake_functions[] */
};
/* }}} */

/* {{{ snowflake_module_entry
 */
zend_module_entry snowflake_module_entry = {
	STANDARD_MODULE_HEADER,
	"snowflake",
	snowflake_functions,
	PHP_MINIT(snowflake),
	PHP_MSHUTDOWN(snowflake),
	PHP_RINIT(snowflake),		/* Replace with NULL if there's nothing to do at request start */
	PHP_RSHUTDOWN(snowflake),	/* Replace with NULL if there's nothing to do at request end */
	PHP_MINFO(snowflake),
	PHP_SNOWFLAKE_VERSION,
	STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_SNOWFLAKE
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(snowflake)
#endif

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: noet sw=4 ts=4 fdm=marker
 * vim<600: noet sw=4 ts=4
 */
